const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject);
        } catch (e) {
            this.reject(e);
        }
    }
    // 状态
    status = PENDING;
    // 成功的值
    value = undefined;
    // 失败的原因
    reason = undefined;
    // 成功回回调
    successCallback = [];
    // 失败回调
    failCallback = [];
    resolve = value => {
        // 只能从 pending 改变，所以判断
        if (this.status != PENDING) return;
        // 改变状态
        this.status = FULFILLED;
        // 修改成功的值
        this.value = value;
        // // 判断成功回调是否存在 如果存在 调用
        // this.successCallback && this.successCallback(this.value);
        while (this.successCallback.length) {
            this.successCallback.shift()();
        }
    }
    reject = reason => {
        // 只能从 pending 改变，所以判断
        if (this.status != PENDING) return;
        // 改变状态
        this.status = REJECTED;
        // 修改失败的原因
        this.reason = reason;
        // 判断失败回调是否存在 如果存在 调用
        // this.failCallback && this.failCallback(this.value);
        while (this.failCallback.length) {
            this.failCallback.shift()();
        }
    }
    then (successCallback, failCallback) {
        successCallback = typeof successCallback == 'function' ? successCallback : value => value;
        failCallback = typeof failCallback == 'function' ? failCallback : reason => { throw reason };

        const promise2 = new MyPromise((resolve, reject) => {
            if (this.status == FULFILLED) {
                // promise2 在 resolve 或者 reject 以后才存在, 所以加一个宏任务，等微任务执行完
                setTimeout(() => {
                    // try catch 捕获当前 then 的错误，抛给下一个 catch
                    try {
                        const x = successCallback(this.value);
                        // 判断 x 的值是普通值还是 promise 对象
                        // 如果是普通值，直接调用 resolve
                        // 如果是 promise 对象 查看 promise 对象返回的结果
                        // 再根据 promise 对象返回的结果，决定用 resolve 还是 reject
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        console.log('e', e)
                        reject(e);
                    }
                }, 0);
            } else if (this.status == REJECTED) {
                setTimeout(() => {
                    // try catch 捕获当前 then 的错误，抛给下一个 catch
                    try {
                        const x = failCallback(this.reason);
                        // 判断 x 的值是普通值还是 promise 对象
                        // 如果是普通值，直接调用 resolve
                        // 如果是 promise 对象 查看 promise 对象返回的结果
                        // 再根据 promise 对象返回的结果，决定用 resolve 还是 reject
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                }, 0);
            } else {
                // 等待
                // 将成功回调和失败回调存起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        // try catch 捕获当前 then 的错误，抛给下一个 catch
                        try {
                            const x = successCallback(this.value);
                            // 判断 x 的值是普通值还是 promise 对象
                            // 如果是普通值，直接调用 resolve
                            // 如果是 promise 对象 查看 promise 对象返回的结果
                            // 再根据 promise 对象返回的结果，决定用 resolve 还是 reject
                            resolvePromise(promise2, x, resolve, reject);
                        } catch (e) {
                            reject(e);
                        }
                    }, 0);
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        // try catch 捕获当前 then 的错误，抛给下一个 catch
                        try {
                            const x = failCallback(this.reason);
                            // 判断 x 的值是普通值还是 promise 对象
                            // 如果是普通值，直接调用 resolve
                            // 如果是 promise 对象 查看 promise 对象返回的结果
                            // 再根据 promise 对象返回的结果，决定用 resolve 还是 reject
                            resolvePromise(promise2, x, resolve, reject);
                        } catch (e) {
                            reject(e);
                        }
                    }, 0);
                });
            }
        });
        
        return promise2;
    }
    catch(failCallback) {
        return this.then(undefined, failCallback);
    }
    finally(callback) {
        return this.then((value) => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason });
        })
    }
    static all(array) { 
        const result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index == array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                const current = array[i];
                console.log('i', i, current instanceof MyPromise);
                if (current instanceof MyPromise) {
                    // promise 对象
                    current.then(value => {
                        console.log('value ==', value);
                        addData(i, value);
                    }, reason => {
                        reject(reason);
                    });
                } else {
                    // 普通值
                    addData(i, array[i]);
                }
            }
        });
    }
    static resolve(value) {
        if (value instanceof MyPromise) {
            return value;
        } else {
            return new MyPromise((resolve, reject) => {
                resolve(value);
            });
        }
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 == x) {
        return reject(new TypeError('chaining cycle'));
    }
    if (x instanceof MyPromise) {
        // x.then(value => {
        //     resolve(value);
        // }, reason => {
        //     reject(reason);
        // })
        x.then(resolve, reject);
    } else {
        resolve(x);
    }
}

module.exports = MyPromise;
